var sys = require('sys'),
    stats = require('../stats');

/**
 *
 */
var PingStatCollector = exports.PingStatCollector = function(config) {
  config.type = 'ping';
  this.count = config.count || 1;
  
  stats.StatCollector.call(this, config);
};
process.inherits(PingStatCollector, stats.StatCollector);

/**
 * 
 */
PingStatCollector.prototype.run = function(callback) {
  sys.exec('ping -c '+this.count+' '+this.config.hostname, function(err, stdout, stderr) {
    if(err) {
      var msg = null;

      if(stderr && stderr.length > 0) {
        msg = stderr.replace(/\n/,'').match(/.*\:(.*)/)[1];
      } else {
        var lines = stdout.split('\n');
        msg = lines[lines.length - 3];
      }

      callback({
        success: false,
        errmsg: msg
      });

    } else {
      var lines = stdout.split('\n');
      for(i =0 ;i<lines.length;i++) {
        var matches = lines[i].match(/^rtt.*=\ (\d+\.\d+)\/(\d+\.\d+)\/(\d+\.\d+)\/(\d+\.\d+).*/);
        if(matches && matches.length === 5) {
          callback({
            success: true,
            data: {
              min: parseInt(matches[1]),
              avg: parseInt(matches[2]),
              max: parseInt(matches[3]),
              mdev: parseInt(matches[4])
            }
          });
          break;
        }
      }
    }
  });
};
